/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AdminCicloCurso.java
 *
 * Created on 15/07/2012, 08:08:42 PM
 */

package interfaz;

import Clases.Ciclocurso;
import Controladores.CiclocursoJpaController;
import escuela.conexion;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author DeLeon
 */
public class AdminCicloCurso extends javax.swing.JDialog {

    conexion cnx = conexion.ObtenerInstancia();
    EntityManagerFactory emf = cnx.ObtenerEMF();
    EntityManager em = emf.createEntityManager();
    CiclocursoJpaController CicloCursos = new CiclocursoJpaController(emf);
    Ciclocurso actual, seleccionado;
    Mensajes msj = new Mensajes(this);
    /** Creates new form AdminCicloCurso */

    public void CargarTabla()
    {
        Object[] datos= new Object[2];
        DefaultTableModel modelo = new DefaultTableModel();
        modelo.addColumn("Id");
        modelo.addColumn("Año");
        List<Ciclocurso> listacurso = CicloCursos.findCiclocursoEntities();
            for(Ciclocurso i: listacurso)
            {
                datos[0]=i.getIdCicloCurso();
                datos[1]=i.getAño();
                modelo.addRow(datos);
            }
        this.jTable1.setModel(modelo);
    }

    private void IngresarCurso()
    {
        int año = this.jYearChooser1.getYear();
        if(año>2011)
        {
            Ciclocurso nuevo = new Ciclocurso((short)CicloCursos.GenerarId(), año);
            CicloCursos.create(nuevo);
            JOptionPane.showMessageDialog(null, "Se ha ingresado el Ciclo Correctamente");
        }
        else
        {
            JOptionPane.showMessageDialog(null, "Ingrese el año Actual o un año futuro");
        }
    }

    private void ModificarCurso()
    {
        int filaseleccionada = this.jTable1.getSelectedRow();
        if(filaseleccionada > -1)
        {
            try
            {
                if(this.jYearChooser2.getYear()>0)
                {
                    Short idCurso= (Short) this.jTable1.getValueAt(filaseleccionada,0);
                    actual=CicloCursos.findCiclocurso(idCurso);
                    int añonuevo= this.jYearChooser2.getYear();
                    actual.setAño(añonuevo);
                    try {
                        CicloCursos.edit(actual);
                    } catch (Exception ex) {
                        Logger.getLogger(AdminCurso.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    JOptionPane.showMessageDialog(null, "Se ha modificado el ciclo Correctamente");
                }
                else
                {
                    JOptionPane.showMessageDialog(null, "Ingrese un año actual o un año futuro");
                }
            }
            catch (Exception ex) {
                    Logger.getLogger(AdminCurso.class.getName()).log(Level.SEVERE, null, ex);
                }
        }
        else
        {
            JOptionPane.showMessageDialog(null, "Seleccione Fila");
        }
    }

    private void Aceptar(){
        int selec = this.Pestaña.getSelectedIndex();
        switch(selec){
            case 0:
                    IngresarCurso();
                    break;
            case 1:
                    ModificarCurso();
                    break;
        }
        this.CargarTabla();
    }

    private void Cancelar(){
        int selec = this.Pestaña.getSelectedIndex();
        byte respuesta;
        switch(selec){
            case 0: respuesta =msj.MensajeConfirmacion("¿Esta seguro que cancelar el ingreso? Todos los datos se perderan");
                    switch(respuesta){
                        case 0: this.jYearChooser1.setYear(2012); break;
                    }
                    break;
            case 1: respuesta = msj.MensajeConfirmacion("¿Esta seguro que desea cancelar la actualizacion? Todos los datos que no esten guardados se perderan");
                    switch(respuesta){
                        case 0: this.jYearChooser2.setYear(this.seleccionado.getAño());
                                break;
                    }
                    break;
        }
    }




    public AdminCicloCurso(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);
        this.CargarTabla();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jButton1 = new javax.swing.JButton();
        jTaskPane1 = new com.l2fprod.common.swing.JTaskPane();
        jLabel1 = new javax.swing.JLabel();
        informacion = new javax.swing.JLabel();
        Pestaña = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel12 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jYearChooser1 = new com.toedter.calendar.JYearChooser();
        jPanel2 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        NoVigente = new javax.swing.JRadioButton();
        SiVigente = new javax.swing.JRadioButton();
        jYearChooser2 = new com.toedter.calendar.JYearChooser();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        aceptar = new javax.swing.JButton();
        cancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Control del Ciclo de Curso");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jButton1.setText("jButton1");

        jLabel1.setFont(new java.awt.Font("Arial", 1, 14));
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setText("Control del Ciclo de los Cursos");
        jTaskPane1.add(jLabel1);

        informacion.setForeground(new java.awt.Color(255, 255, 255));
        informacion.setText("jLabel2");
        jTaskPane1.add(informacion);

        Pestaña.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                PestañaStateChanged(evt);
            }
        });
        Pestaña.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                PestañaFocusGained(evt);
            }
        });

        jLabel12.setForeground(new java.awt.Color(255, 0, 0));
        jLabel12.setText("*");
        jLabel12.setToolTipText("Campo Obligatorio");

        jLabel3.setFont(new java.awt.Font("Arial", 0, 12));
        jLabel3.setText("Año:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(102, 102, 102)
                .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 6, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jYearChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(104, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 62, Short.MAX_VALUE)
                    .addComponent(jLabel12, javax.swing.GroupLayout.DEFAULT_SIZE, 72, Short.MAX_VALUE)))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jYearChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(28, 28, 28))
        );

        Pestaña.addTab("Crear", jPanel1);

        jLabel4.setFont(new java.awt.Font("Arial", 0, 12));
        jLabel4.setText("Año:");

        jLabel5.setFont(new java.awt.Font("Arial", 0, 12));
        jLabel5.setText("Vigente:");

        buttonGroup1.add(NoVigente);
        NoVigente.setFont(new java.awt.Font("Arial", 0, 12));
        NoVigente.setText("No");
        NoVigente.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                NoVigenteKeyPressed(evt);
            }
        });

        buttonGroup1.add(SiVigente);
        SiVigente.setFont(new java.awt.Font("Arial", 0, 12));
        SiVigente.setSelected(true);
        SiVigente.setText("Si");
        SiVigente.setOpaque(false);
        SiVigente.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                SiVigenteKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(87, 87, 87)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(jLabel4))
                .addGap(16, 16, 16)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(SiVigente)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(NoVigente))
                    .addComponent(jYearChooser2, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(108, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(16, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4)
                    .addComponent(jYearChooser2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(SiVigente)
                    .addComponent(NoVigente))
                .addContainerGap())
        );

        Pestaña.addTab("Editar", jPanel2);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "Año"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Short.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        aceptar.setText("Aceptar");
        aceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aceptarActionPerformed(evt);
            }
        });
        aceptar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                aceptarKeyPressed(evt);
            }
        });

        cancelar.setText("Cancelar");
        cancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarActionPerformed(evt);
            }
        });
        cancelar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                cancelarKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTaskPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 362, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 342, Short.MAX_VALUE)
                    .addComponent(Pestaña, javax.swing.GroupLayout.DEFAULT_SIZE, 342, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(cancelar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(aceptar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jTaskPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(Pestaña, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(aceptar)
                    .addComponent(cancelar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void NoVigenteKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_NoVigenteKeyPressed
        // TODO add your handling code here:
        if(evt.getKeyCode()==10){
            this.cancelar.requestFocusInWindow();
        }
}//GEN-LAST:event_NoVigenteKeyPressed

    private void SiVigenteKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_SiVigenteKeyPressed
        // TODO add your handling code here:
        if(evt.getKeyCode()==10){
            this.NoVigente.setSelected(true);
        }
}//GEN-LAST:event_SiVigenteKeyPressed

    private void PestañaStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_PestañaStateChanged
        // TODO add your handling code here:
        if(this.Pestaña.getSelectedIndex()==1) {
            this.informacion.setText("Seleccione un año de la tabla, para modificarlo");
            this.aceptar.setEnabled(true);
            this.cancelar.setEnabled(true);
        } else if(this.Pestaña.getSelectedIndex()==0){
            this.informacion.setText("Creacion de un nuevo año, los campos con * son obligatorios");
            this.aceptar.setEnabled(true);
            this.cancelar.setEnabled(true);
        }
}//GEN-LAST:event_PestañaStateChanged

    private void PestañaFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_PestañaFocusGained
        // TODO add your handling code here:
    }//GEN-LAST:event_PestañaFocusGained

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        // TODO add your handling code here:
        int filaseleccionada = this.jTable1.getSelectedRow();
        if(filaseleccionada > -1) {
            try {
                Short idCurso= (Short) this.jTable1.getValueAt(filaseleccionada,0);
                this.seleccionado=CicloCursos.findCiclocurso(idCurso);
                this.jYearChooser2.setYear(this.seleccionado.getAño());
            } catch (Exception ex) {
                Logger.getLogger(AdminCurso.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            JOptionPane.showMessageDialog(null, "Seleccione Fila");
        }
}//GEN-LAST:event_jTable1MouseClicked

    private void aceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aceptarActionPerformed
        // TODO add your handling code here:
        Aceptar();
}//GEN-LAST:event_aceptarActionPerformed

    private void aceptarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_aceptarKeyPressed
        // TODO add your handling code here:
        if(evt.getKeyCode()==10){
            Aceptar();
        }
}//GEN-LAST:event_aceptarKeyPressed

    private void cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarActionPerformed
        // TODO add your handling code here:
        Cancelar();
}//GEN-LAST:event_cancelarActionPerformed

    private void cancelarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cancelarKeyPressed
        // TODO add your handling code here:
        if(evt.getKeyCode()==10){
            Cancelar();
        }
}//GEN-LAST:event_cancelarKeyPressed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        emf.close();
    }//GEN-LAST:event_formWindowClosing

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                AdminCicloCurso dialog = new AdminCicloCurso(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JRadioButton NoVigente;
    private javax.swing.JTabbedPane Pestaña;
    private javax.swing.JRadioButton SiVigente;
    private javax.swing.JButton aceptar;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton cancelar;
    private javax.swing.JLabel informacion;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private com.l2fprod.common.swing.JTaskPane jTaskPane1;
    private com.toedter.calendar.JYearChooser jYearChooser1;
    private com.toedter.calendar.JYearChooser jYearChooser2;
    // End of variables declaration//GEN-END:variables

}
